package com.egao.common.core.damon.utils;

import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author: Damon
 * @date: Sep 15, 2014 3:20:19 PM 
 * @version : 1
 */

public class Utils {
	/**
	 * 
	 * @return
	 */
	public static boolean isNotEmpty(Object obj) {
		if (obj != null ) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * @param num
	 * @return
	 */
	public static boolean isNotEmpty(Integer num) {
		if (num != null) {
			return true;
		}
		return false;
	}
	/**
	 * 
	 * @param string
	 * @return
	 */
	public static boolean isNotEmpty(String string) {
		if (string != null && string.trim().length() != 0) {
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * @return
	 */
	public static boolean isNotEmpty(Collection<Object> collection) {
		if (collection == null) {
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * @return
	 */
	public static boolean isNotEmpty(@SuppressWarnings("rawtypes") List list) {
		if (list == null || list.size() == 0) {
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public static boolean isNotEmpty(Map<String, Object> map) {
		if (map == null) {
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * @param string
	 * @return
	 */
	public static boolean isEmpty(String string) {
		if (string == null || string.length() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @return
	 */
	public static boolean isEmpty(Collection<Object> collection) {
		if (collection == null) {
			return true;
		}
		return collection.isEmpty();
	}

	/**
	 * 
	 * @return
	 */
	public static boolean isEmpty(List<Object> list) {
		if (list == null) {
			return true;
		}
		return list.isEmpty();
	}
	
	/**
	 * 
	 * @return
	 */
	public static boolean isEmpty(Map<String, Object> map) {
		if (map == null) {
			return true;
		}
		return map.isEmpty();
	}

	/**
	 * 
	 * @param method
	 * @return
	 */
	public static boolean isGetter(Method method) {
		String methodName = method.getName();
		Object[] o = method.getParameterTypes();
		if(methodName.startsWith("get") && o.length==0){
			return true;
		}
		return false;
	}
	
	/**
	 * 
	 * @return
	 */
	public static Date getCurrentDate() {
		return new Date();
	}
	
	/**
	 * 
	 * @return
	 */
	public static Timestamp getCurrentTimestamp() {
		return new Timestamp(getCurrentDate().getTime());
	}
	
	/**
	 * @return Integer
	 */
	public static Integer getWeekDifference(Date startDate, Date endDate) {
		 if(startDate == null) return null;
         if(endDate == null) endDate = new Date();
         long diff = endDate.getTime() - startDate.getTime();
         long days = diff / (1000 * 60 * 60 * 24 * 7);
		 return Integer.valueOf(days+"");
	}
	
	/**
	 * @return Integer
	 */
	public static Integer getMonthDifference(Date startDate, Date endDate) {
		 int countMonth;
		 if(startDate == null) return null;
         if(endDate == null) endDate = new Date();
         Calendar calendar= GregorianCalendar.getInstance();
         calendar.setTime(endDate);
         int endYear = calendar.get(Calendar.YEAR);
         int endMonth = calendar.get(Calendar.MONTH)+1;
         int endDay = calendar.get(Calendar.DAY_OF_MONTH);
         calendar.setTime(startDate);
         int startYear = calendar.get(Calendar.YEAR);
         int startMonth = calendar.get(Calendar.MONTH)+1;
         int startDay = calendar.get(Calendar.DAY_OF_MONTH);
         int diffYear = endYear - startYear;
         int diffMonth = endMonth - startMonth;
         if(endDay < startDay){
        	 countMonth=diffYear*12 + diffMonth - 1;
         }else{
        	 countMonth=diffYear*12+diffMonth;
         }
		 return Integer.valueOf(countMonth);
	}

	
	/**
	 * @return Integer
	 */
	public static Integer getYear(Date date) {
		 if(date == null) return null;
         Calendar calendar= GregorianCalendar.getInstance();
         calendar.setTime(date);
         return new Integer(calendar.get(Calendar.YEAR));
	}

	/**
	 * 
	 * @param fromObj
	 * @param toObj
	 */
	public static void copyFields(Object fromObj, Object toObj) {
		Method[] methods = fromObj.getClass().getMethods();
		for (Method method : methods) {
			if (isGetter(method)) {
				String methodName = method.getName();
				String setterName = methodName.replaceFirst("get", "set");
				try {
					Method setterMethod = toObj.getClass().getMethod(setterName,
							new Class[] { method.getReturnType() });
					Object value = method.invoke(fromObj);
					setterMethod.invoke(toObj, value);
				} catch (Exception e) {
					// do nothing
				}
			}
		}
	}

	/**
	 * 
	 * @param fromMap
	 * @param toObj
	 */
	public static void copyFields(Map<String, Object> fromMap, Object toObj){
		 Field[] fields = toObj.getClass().getDeclaredFields();
		 Set<String> set = fromMap.keySet();
		 for(Iterator<String> iter = set.iterator(); iter.hasNext();){
		   String key = (String)iter.next();
		   Object value = (Object)fromMap.get(key);
		   for (Field field : fields) {
				if (field.getName().equals(key)) {
					try {
						if(field.getType().isInstance(value)){
							field.setAccessible(true);
							field.set(toObj, value);
						}
					} catch (Exception e) {
						// do nothing
					}
				}
			}
		  }
	 }
	 /**
	  * 
	  * @param fromObj
	  * @param toMap
	  */
     public static void copyFields(Object fromObj, Map<String, Object> toMap){
    	 Field[] fields = fromObj.getClass().getDeclaredFields();
    	 for (Field field : fields) {
    		 try {
    			field.setAccessible(true);
    			String fieldName = field.getName();
    			Object value = getFieldValueByName(fieldName,fromObj);
    			if(value!=null){
    				toMap.put(fieldName, value);
    			}
    		 } catch (Exception e) {
					// do nothing
			}
    	 }
     }

	
     private static Object getFieldValueByName(String fieldName, Object o) {
         try {    
             String firstLetter = fieldName.substring(0, 1).toUpperCase();
             String getter = "get" + firstLetter + fieldName.substring(1);
             Method method = o.getClass().getMethod(getter, new Class[] {});
             Object value = method.invoke(o, new Object[] {});
             return value;    
         } catch (Exception e) {
             return null;    
         }    
     }
     
	/**
	 * 
	 * @param obj
	 * @return
	 */
	public static String toString(Object obj) {

		StringBuffer strToReturn = new StringBuffer();
		PropertyDescriptor[] propDescs = PropertyUtils
				.getPropertyDescriptors(obj);
		String className = obj.getClass().getName();
		String[] cn = className.split("\\.");
		className = cn[cn.length - 1];
		strToReturn.append(className + "{ ");
		for (int i = 0; i < propDescs.length; i++) {
			String propName = propDescs[i].getName();

			if (PropertyUtils.isReadable(obj, propName)
					&& PropertyUtils.isWriteable(obj, propName)) {

				strToReturn.append(propName + "=");
				try {
					Object value = PropertyUtils.getProperty(obj, propName);
					if (i == propDescs.length - 2) {
						strToReturn.append(value);
					} else {
						strToReturn.append(value + ", ");
					}

				} catch (Exception e) {
					strToReturn.append("");
				}
			}
		}
		strToReturn.append(" } ");
		return strToReturn.toString();
	}
	
	public static Date getDateValue(Timestamp ts){
		Date date = new Date(ts.getTime());
		return date;
	}


	public static BigDecimal add(BigDecimal bd1, BigDecimal bd2) {
		if (bd1 == null) {
			return bd2;
		}
		if (bd2 == null) {
			return bd1;
		}
		return bd1.add(bd2);
	}

	public static String twoDot(float bd1) {
		return new DecimalFormat("#.00").format(bd1);
	}
	
	public static String htmlspecialchars(String str) {
		str = str.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
		return str;
	}


}

